package org.yu.api.register.codec;

import com.google.gson.*;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.block.Blocks;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.reflect.Type;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class IngredientCodec implements JsonSerializer<Ingredient>, JsonDeserializer<Ingredient> {


    public static Ingredient fromJson(@Nullable JsonElement pJson) {
        if (pJson != null && !pJson.isJsonNull()) {
            if (pJson.isJsonObject()) {
                return Ingredient.fromValues(Stream.of(Ingredient.valueFromJson(pJson.getAsJsonObject())));
            } else if (pJson.isJsonArray()) {
                JsonArray jsonarray = pJson.getAsJsonArray();
                if (jsonarray.size() == 0) {
                    return Ingredient.EMPTY;
                } else {
                    return Ingredient.fromValues(StreamSupport.stream(jsonarray.spliterator(), false).map((p_151264_) -> Ingredient.valueFromJson(GsonHelper.convertToJsonObject(p_151264_, "item"))));
                }
            } else {
                throw new JsonSyntaxException("Expected item to be object or array of objects");
            }
        } else {
            throw new JsonSyntaxException("Item cannot be null");
        }
    }

    @Override
    public Ingredient deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
       return fromJson(json);
    }

    @Override
    public JsonElement serialize(@Nonnull Ingredient src, Type typeOfSrc, JsonSerializationContext context) {
        return src.toJson();
    }
}
